package io.github.kimmking.gateway.outbound.okhttp;

import io.github.kimmking.gateway.constant.GConstant;
import io.github.kimmking.gateway.inbound.HttpInboundHandler;
import io.github.kimmking.gateway.outbound.netty.NettyHttp;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.Promise;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @ClassName HttpResponse
 * @Description
 * @Author Jingxiao.Ye
 * @Date 2021/11/21 下午10:57
 * @Version V1.0
 * @Since JDK 11
 */
public class HttpResponse implements Callback {

    private static Logger logger = LoggerFactory.getLogger(HttpResponse.class);

    private Promise<FullHttpResponse> fullHttpResponse;

    private final ChannelHandlerContext ctx;
    private final HttpVersion httpVersion;

    public HttpResponse(final ChannelHandlerContext ctx, HttpVersion httpVersion) {
        //传入线程池返回
        this.ctx = ctx;
        this.httpVersion = httpVersion;
        this.fullHttpResponse = new DefaultPromise<>(NettyHttp.eventExecutor);
    }

    public FullHttpResponse getFullHttpResponse(long timout) {
        try {
            FullHttpResponse response = fullHttpResponse.get(timout, TimeUnit.MILLISECONDS);
            return response;
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            return new DefaultFullHttpResponse(httpVersion, HttpResponseStatus.NOT_FOUND);
        }
    }

    @Override
    public void onFailure(Call call, IOException e) {
        logger.error("请求失败,{},错误信息,{}", call.request(), e);
        DefaultFullHttpResponse defaultFullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        fullHttpResponse.setSuccess(defaultFullHttpResponse);
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        //执行返回代码u
        ResponseBody body = response.body();
        ByteBuf byteBuf = ctx.alloc().buffer().writeBytes(body.bytes());
        Headers headers = response.headers();
        DefaultFullHttpResponse defaultFullHttpResponse = new DefaultFullHttpResponse(httpVersion, HttpResponseStatus.OK, byteBuf);
        HttpHeaders httpHeaders = defaultFullHttpResponse.headers();
        for (Map.Entry<String, List<String>> entry : headers.toMultimap().entrySet()) {
            httpHeaders.add(entry.getKey(), entry.getValue());
        }
        fullHttpResponse.setSuccess(defaultFullHttpResponse);
    }
}
